package com.cloud.tsp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.api.domain.service.*;
import com.cloud.core.exception.MyException;
import com.cloud.core.util.R;
import com.cloud.tsp.config.SmsCodeVerify;
import com.cloud.tsp.mapper.ContactHistoryMapper;
import com.cloud.tsp.mapper.StationAuditRecordMapper;
import com.cloud.tsp.mapper.StationServiceBaseInfoMapper;
import com.cloud.tsp.service.IContactHistoryService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.List;

/**
 * @author 杨斌
 * 2025-03-2025-03-10
 */
@Service("contactHistoryService")
public class ContactHistoryServiceImpl extends ServiceImpl<ContactHistoryMapper, ContactHistory> implements IContactHistoryService {

    @Resource
    private ContactHistoryMapper contactHistoryMapper;
    @Resource
    private StationServiceBaseInfoMapper stationServiceBaseInfoMapper;

    @Resource
    private StationAuditRecordMapper stationAuditRecordMapper;

    @Resource(name = "myRedis")
    private RedisTemplate<String, Object> redisTemplate;


    @Resource
    private SmsCodeVerify smsCodeVerify;
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public R updateContact(UpdateContactRequest para) {


        String code = para.getVerificationCode();
        String phone = para.getNewContactPhone();

        String serviceStationName = para.getServiceStationName();

        LambdaQueryWrapper<StationServiceBaseInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StationServiceBaseInfo::getName, serviceStationName);

        StationServiceBaseInfo stationServiceBaseInfo = stationServiceBaseInfoMapper.selectOne(queryWrapper);

        if (stationServiceBaseInfo == null) {
            throw new MyException("wds.exception.stationNotFound");
        }
        // 检查该服务站是否有待审核记录
        String stationServiceId = stationServiceBaseInfo.getId();

        LambdaQueryWrapper<ContactHistory> query = new LambdaQueryWrapper<>();
        query.eq(ContactHistory::getServiceStationId, stationServiceId);
        List<String> contactHistoryIds = contactHistoryMapper.selectList(query).stream().map(ContactHistory::getId).toList();
        // 通过 contactHistoryIds 检查是否有未审核的记录
        // 检查 contactHistoryIds 是否为空
        if (!contactHistoryIds.isEmpty()) {
            LambdaQueryWrapper<StationAuditRecord> auditQuery = new LambdaQueryWrapper<>();
            auditQuery.in(StationAuditRecord::getContactHistoryId, contactHistoryIds)
                    .eq(StationAuditRecord::getAuditStatus, 0);  // 0 表示待审核
            List<StationAuditRecord> pendingAuditRecords = stationAuditRecordMapper.selectList(auditQuery);

            if (!pendingAuditRecords.isEmpty()) {
                throw new MyException("wds.exception.duplicate");
            }
        }

        LambdaQueryWrapper<StationServiceBaseInfo> phoneQuery = new LambdaQueryWrapper<>();
        phoneQuery.eq(StationServiceBaseInfo::getContactPhone, phone);

        StationServiceBaseInfo stationServiceInfo = stationServiceBaseInfoMapper.selectOne(phoneQuery);

        if (stationServiceInfo != null) {
            throw new MyException("wds.exception.stationPhoneExist");
        }
        // 验证验证码
        smsCodeVerify.verifySmsCode(phone, code);

        String serviceStationId = stationServiceBaseInfo.getId();

        ContactHistory contactHistory = new ContactHistory();

        BeanUtils.copyProperties(para, contactHistory);
        contactHistory.setOldContactPerson(stationServiceBaseInfo.getContactPerson());
        contactHistory.setOldContactPhone(stationServiceBaseInfo.getContactPhone());
        contactHistory.setServiceStationId(serviceStationId);

        contactHistoryMapper.insert(contactHistory);
        String id = contactHistory.getId();
        StationAuditRecord auditRecord = new StationAuditRecord();
        auditRecord.setContactHistoryId(id);
        stationAuditRecordMapper.insert(auditRecord);
        return R.ok();
    }

    public void verifySmsCode(String phone, String code) {
        String redisCodeKey = "SERVICE_STATION:" + phone + ":code";
        String redisUsedKey = "SERVICE_STATION:" + phone + ":used";

        // 获取存储的验证码和使用状态
        String storedCode = (String) redisTemplate.opsForValue().get(redisCodeKey);
        String used = (String) redisTemplate.opsForValue().get(redisUsedKey);

        // 验证验证码是否为空
        if (code == null || code.trim().isEmpty()) {
            throw new MyException("wds.exception.verificationFailed");
        }

        // 验证验证码是否过期
        if (storedCode == null) {
            throw new MyException("wds.exception.verificationExpired");
        }

        // 验证验证码是否一致
        if (!storedCode.equals(code)) {
            throw new MyException("wds.exception.verificationError");
        }

        // 验证验证码是否已使用
        if ("true".equals(used)) {
            throw new MyException("wds.exception.verificationUsed");
        }

        // 验证码正确且未使用，标记为已使用
        redisTemplate.opsForValue().set(redisUsedKey, "true", Duration.ofMinutes(5));
    }
    @Override
    public List<ServiceStationInfo> getContactInformation() {

        return contactHistoryMapper.getContactInformation();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public R auditContact(AuditRequest para) {


        String auditRecordId = para.getAuditRecordId();
        StationAuditRecord auditRecord = stationAuditRecordMapper.selectById(auditRecordId);

        if (auditRecord == null) {
            return R.failed("未找到对应的审核记录");
        }

        auditRecord.setAuditStatus(para.getAuditStatus());
        stationAuditRecordMapper.updateById(auditRecord);

        switch (para.getAuditStatus()) {
            case 1: // 审核通过
                String serviceStationId = para.getServiceStationId();
                StationServiceBaseInfo serviceBaseInfo = stationServiceBaseInfoMapper.selectById(serviceStationId);
                if (serviceBaseInfo != null) {
                    serviceBaseInfo.setContactPerson(para.getNewContactPerson());
                    serviceBaseInfo.setContactPhone(para.getNewContactPhone());
                    stationServiceBaseInfoMapper.updateById(serviceBaseInfo);
                }
                return R.ok("审核通过，数据已更新");
            case 2: // 驳回
                return R.ok("审核驳回");
            default:
                return R.failed("无效的审核状态");
        }
    }


}
